/*
 * @lc app=leetcode.cn id=54 lang=javascript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
    if (matrix.length === 0) return []
    let res = []
    let top = 0
    let right = matrix[0].length - 1
    let bottom = matrix.length - 1
    let left = 0

    while (left < right && top < bottom) {
        for (let a = left; a < right; a++) {
            res.push(matrix[top][a])
        }
        for (let b = top; b < bottom; b++) {
            res.push(matrix[b][right])
        }
        for (let c = right; c > left; c--) {
            res.push(matrix[bottom][c])
        }
        for (let d = bottom; d > top; d--) {
            res.push(matrix[d][left])
        }
        top++
        right--
        bottom--
        left++
    }
    if (top === bottom) {
        for (let a = left; a < right; a++) {
            res.push(matrix[top][a])
        }
    } else if (left === right) {
        for (let b = top; b < bottom; b++) {
            res.push(matrix[b][right])
        }
    }

    return res
};
// @lc code=end

